# 写一个三乐购物系统，功能使用函数封装
# 1、欢迎界面
#   1、登录
#      输入用户名和密码
#      和系统里保存的用户信息比较，判断用户和密码是否合法
#      登录失败，返回上一级
#      登录成功：
#       1、查看商品
#       2、加入购物车 2->(001~005)
#       3、结算购物车
#       4、返回上一级
#   2.注册
#      用户名、用户密码、用户存入金额
#      用户信息固化
#   3、退出

import json
import os

# 登录功能
def loading():
    username = input("please your username:")
    password = input("please your password:")
    #验证用户名和密码是否正确
    if username in name_dict and name_dict[username]['password'] == password:
        print("登录成功！")
        print("您能使用的金额为:", name_dict[username]["savings"])
        #登录成功后，读取商品信息
        file_path1 = "goods.txt"
        goods_dict = {}
        # 判断文件是否存在，若不存在就用空字典，存在则读取里面的内容
        if os.path.exists(file_path1):
            fp = open(file_path1)
            goods_str = fp.read()
            goods_dict = json.loads(goods_str)
        while True:
            #如果是root管理员能添加商品
            if username == "root":
                print("1.请添加商品\n2.返回上一级\n")
                m = input("Please make a choice:")
                if m == "1":
                    add1(goods_dict)
                elif m == "2":
                    break
                else:
                    print("输入错误，重新输入\n")
            #其它用户能购物
            else:
                print("1.查看商品\n2.加入购物车\n3.结算购物车\n4.返回上一级\n")
                n = input("Please make a choice:")
                if n == "1":
                    print(goods_dict)
                elif n == "2":
                    commodity_dict = join1(username, goods_dict)
                    print("你已选择的商品:", commodity_dict[username])
                elif n == "3":
                    spent = settle(username, goods_dict)
                    # 判断花费是否为0，来确定购物车是否有商品
                    if spent != 0:
                        name_dict[username]['savings'] = name_dict[username]['savings'] - spent
                        print(f"您这次消费了{spent}元，还剩下{name_dict[username]['savings']}")
                        write1(name_dict)
                elif n == "4":
                    break
                else:
                    print("输入错误，重新输入\n")


    else:
        print("用户名或密码错误\n")

#注册功能
def regist():
    username = input("please your username:")
    #判断用户是否注册
    if username in name_dict:
        print("该用户已被注册\n")
    #没注册去注册
    else:
        password = input("please your password:")
        savings = int(input("please your saving(isdigit):"))
        name_dict[username] = {"password": password, "savings": savings}
        print("用户注册成功，请登录！\n")
        write1(name_dict)

#固化用户信息功能
def write1(name_dict):
    fp = open("user.txt", "w")
    result_str = json.dumps(name_dict)
    fp.write(result_str)
    fp.flush()
#添加商品的功能
def add1(goods_dict):
    while True:
        goods_name = input("please your goods_name:")
        if goods_name == "q":
            break
        goods_price = int(input("please your good_price:"))
        if goods_name in goods_dict:
            print("商品已上架")
        else:
            goods_dict[goods_name] = goods_price
    print(f"已上架的商品有{goods_dict}")
    #将商品信息固化
    fp = open("goods.txt", "w")
    result_str = json.dumps(goods_dict)
    fp.write(result_str)
    fp.flush()


# 加入购物车功能
def join1(username, goods_dict):
    commodity_dict = read()
    commodity_lst = []
    while True:
        commodity = input("please select Item name:")
        #如果输入的不是商品就退出
        if commodity not in goods_dict:
            break
        commodity_lst.append(commodity)
    commodity_dict[username] = commodity_lst
    write(commodity_dict)
    return commodity_dict

#结算购物车
def settle(username, goods_dict):
    commodity_dict = read()
    #购物车为空，就返回信息
    if not commodity_dict:
        print("购物车里面没有东西, 请去购物")
        return 0
    # 购物车不为空，就结算商品并清空购物车
    else:
        sum1 = 0
        for i in commodity_dict[username]:
            sum1 = sum1 + goods_dict[i]
        print(f"{commodity_dict[username]}这些商品共花了{sum1}元")
        commodity_dict.pop(username)
        write(commodity_dict)
        return sum1

# 读取购物车信息功能
def read():
    file_path = "shopping.txt"
    commodity_dict = {}
    if os.path.exists(file_path):
        fp = open(file_path)
        commodity_str = fp.read()
        commodity_dict = json.loads(commodity_str)
    return commodity_dict

#记录用户所购商品功能
def write(commodity_dict):
    fp = open("shopping.txt", "w")
    result_str = json.dumps(commodity_dict)
    fp.write(result_str)
    fp.flush()

#读取用户信息
file_path = "user.txt"
name_dict = {}
# 判断文件是否存在，若不存在就用空字典，存在则读取里面的内容
if os.path.exists(file_path):
    fp = open(file_path)
    name_str = fp.read()
    name_dict = json.loads(name_str)

while True:
    print("1.登录\n2.注册\n3.退出\n")
    n = input("Please make a choice:")
    if n == "1":
        loading()
    elif n == "2":
        regist()
    elif n == "3":
        print("退出程序")
        break
    else:
        print("输入错误，重新输入\n")
